import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';

// 用户信息接口
interface UserInfo {
  id?: string;
  auName?: string;
  avatar?: string;
  name?: string;
  email?: string;
  role?: string;
  [key: string]: any;
}

// 聊天会话状态接口
interface ChatSession {
  isFirstChat: boolean; // 是否是初次会话
  chatId?: string; // 聊天助手ID
  sessionId?: string; // 会话ID
  chatList?: any[]; // 聊天记录列表
}

// 全局状态接口
interface StoreState {
  // 用户信息
  userInfo: UserInfo;
  setUserInfo: (userInfo: UserInfo) => void;
  clearUserInfo: () => void;
  
  // 聊天会话状态
  chatSession: ChatSession;
  setChatSession: (chatSession: Partial<ChatSession>) => void;
  setChatFirstTime: (isFirstChat: boolean) => void;
  clearChatSession: () => void;
}

// 创建store
const useStore = create<StoreState>()(  
  devtools(
    persist(
      (set) => ({
        // 用户信息初始状态
        userInfo: {},
        setUserInfo: (userInfo) => set({ userInfo }),
        clearUserInfo: () => set({ userInfo: {} }),
        
        // 聊天会话初始状态
        chatSession: {
          isFirstChat: true,
          chatList: [],
        },
        // 存储session信息
        setChatSession: (chatSession) => 
          set((state) => ({
            chatSession: { ...state.chatSession, ...chatSession }
          })),
        setChatFirstTime: (isFirstChat) => 
          set((state) => ({
            chatSession: { ...state.chatSession, isFirstChat }
          })),
        clearChatSession: () => 
          set({ 
            chatSession: { 
              isFirstChat: true,
              chatList: [] 
            } 
          }),
      }),
      {
        name: 'bio-safe-storage', // localStorage的key名称
        partialize: (state) => ({ 
          userInfo: state.userInfo,
          chatSession: state.chatSession 
        }), // 只持久化这些字段
      }
    )
  )
);

export default useStore;
